import { login, getprofile, getUserbyId } from '@/api/user'
import router from '@/router'
// import { removeToken } from '@/utils/auth'
const state = {
  // 刷新页面先看看本地存储有没有备份
  token: localStorage.getItem('token') || '',
  profile: {}
}
const mutations = {
  setToken(state, data) {
    // 每当将token存入vuex的时候，同时存一份到本地存储
    localStorage.setItem('token', data)
    state.token = data
  },
  setProfile(state, data) {
    state.profile = data
  },
  // 清除数据
  removeToken(state) {
    state.token = ''
    // removeToken()
  },
  removeProfile(state) {
    state.profile = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await login(data)
    // commit需要通过mutations才能操作state
    store.commit('setToken', res)
    // 登录成功记录token的同时要记录时间戳，用主动介入token超时判断
    localStorage.setItem('loginTime', Date.now())
  },
  async getprofile(store) {
    const res = await getprofile()
    const detail = await getUserbyId(res.userId)
    // 当处理多个数据的时候可以使用展开运算符
    store.commit('setProfile', {
      ...res,
      ...detail
    })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeProfile')
    router.push('/login')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

